<?php

namespace App\Http\Controllers\Web;

use App\Models\User;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class UsersController extends Controller
{
    public function index(Request $request)
    {
        $size = $request->input('size', 10);
        $query = User::query();
        $name = $request->input("name");
        $query->when($name, function ($query) use ($name) {
            $query->where('name', "like", "%{$name}%");
        });

        return $this->successPaginate($query->paginate($size));
    }

    public function show($id)
    {
        $team = User::query()->findOrFail($id);
        return $this->success($team);
    }

    public function store(Request $request)
    {
        $this->validate($request, [
            'name' => 'required',
            'password' => 'required',
        ]);
        $user = new User();
        $user->name = $request->name;
        $user->password = bcrypt($request->password);
        $user->save();

        return $this->success($user);
    }

    public function update(Request $request, $id)
    {
        $user = User::query()->findOrFail($id);
        $requestData = $this->validate($request, [
            'name' => 'required',
        ]);
        $name = $request->name;
        $password = $request->password;
        if ($password) {
            $password = bcrypt($request->password);
            $user->fill(['name' => $name, 'password' => $password]);
        } else {
            $user->fill(['name' => $name]);
        }

        $user->save();
        return $this->success($requestData);
    }

    public function destroy($id)
    {
        $team = User::query()->findOrFail($id);
        $team->delete();
    }
}
